package org.jadelyre.core.codec.sun;

import org.jadelyre.core.codec.Codec;
import org.jadelyre.core.codec.Packet;
import org.jadelyre.core.exception.CodecException;

import java.nio.ByteBuffer;

/**
 * 默认编解码器
 */
public class SunCodec implements Codec {

    @Override
    public SunPacket decode(ByteBuffer byteBuffer) throws CodecException {
        int readableLength = byteBuffer.remaining();
        int headerLength = SunHeader.getHeaderLength();
        if (headerLength > readableLength){
            //解析包头长度不够
            return null;
        }
        SunHeader sunHeader = SunHeader.getHeader(byteBuffer);
        int bodyLength = sunHeader.getBodyLength();
        int neededLength = headerLength + bodyLength;
        if (readableLength < neededLength){
            return null;
        }
        //长度够，组装包
        byte[] bytes = new byte[bodyLength];
        byteBuffer.get(bytes);
        return SunPacket.decodeBuild(sunHeader,bytes);
    }

    @Override
    public ByteBuffer encode(Packet packet) throws CodecException {
        SunHeader header = ((SunPacket)packet).getHeader();
        if (header == null){
            throw new CodecException("传输数据包头为空");
        }
        int headerLength = SunHeader.getHeaderLength();
        if (packet.getBody() == null){
            throw new CodecException("传输数据包体数据为空");
        }
        int neededLength = headerLength + packet.getBody().length;
        ByteBuffer byteBuffer = ByteBuffer.allocate(neededLength);
        byteBuffer.put(header.getPacketMark());//先放标识再放消息体长度，与解码时对应
        byteBuffer.putInt(header.getBodyLength());
        byteBuffer.put(packet.getBody());
        byteBuffer.flip();
        return byteBuffer;

    }
}
